package com.tarry.service.impl;

import com.google.common.base.Preconditions;
import com.tarry.common.RequestHolder;
import com.tarry.dao.SysDeptMapper;
import com.tarry.dao.SysUserMapper;
import com.tarry.exception.ParamException;
import com.tarry.model.entity.BaseEntity;
import com.tarry.model.entity.SysDept;
import com.tarry.model.vo.DeptPVo;
import com.tarry.service.SysDeptService;
import com.tarry.service.SysUserService;
import com.tarry.util.BeanValidator;
import com.tarry.util.IpUtil;
import com.tarry.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SysDeptServiceImpl extends BaseService<SysDept> implements SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysDept findByKeyword(String keyword) {
        return null;
    }

    /**
     * 保存部门信息
     *
     * @param deptVO
     */
    @Override
    public void save(DeptPVo deptVO) {
        BeanValidator.check(deptVO);
        if (checkExist(deptVO.getParentId(), deptVO.getName(), deptVO.getId())) {
            throw new ParamException("同级下存在相同部门名称的部门！");
        }
        SysDept dept = SysDept.builder()
                .name(deptVO.getName())
                .parentId(deptVO.getParentId())
                .seq(deptVO.getSeq())
                .remark(deptVO.getRemark())
                .build();
        dept.setLevel(LevelUtil.calculateLevel(getLevel(deptVO.getId()), deptVO.getParentId()));
//        dept.setOperator(RequestHolder.getCurrentUser().getUsername());//
//        dept.setOperatorTime(new Date());
//        dept.setOperatorIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        setOpratorInfo(dept);
        sysDeptMapper.insertSelective(dept);
        //TODO 插入日志
    }

    /**
     * 修改部门信息
     *
     * @param deptPVO
     */
    @Override
    public void update(DeptPVo deptPVO) {
        BeanValidator.check(deptPVO);
        if (checkExist(deptPVO.getParentId(), deptPVO.getName(), deptPVO.getId())) {
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept before = sysDeptMapper.selectByPrimaryKey(deptPVO.getId());
        Preconditions.checkNotNull(before, "待更新的部门不存在");
        if (checkExist(deptPVO.getParentId(), deptPVO.getName(), deptPVO.getId())) {
            throw new ParamException("同一层级下存在相同名称的部门");
        }

        SysDept after = SysDept.builder()
                .id(deptPVO.getId())
                .name(deptPVO.getName())
                .parentId(deptPVO.getParentId())
                .seq(deptPVO.getSeq())
                .remark(deptPVO.getRemark())
                .build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(deptPVO.getParentId()), deptPVO.getParentId()));
//        after.setOperator(RequestHolder.getCurrentUser().getUsername());
//        after.setOperatorIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
//        after.setOperatorTime(new Date());
        setOpratorInfo(after);
        updateWithChild(before, after);
        //sysLogService.saveDeptLog(before, after);
    }

    @Transactional
    @Override
    public void updateWithChild(SysDept before, SysDept after) {
        String newLevelPrefix = after.getLevel();
        String oldLevelPrefix = before.getLevel();
        if (!after.getLevel().equals(before.getLevel())) {
            List<SysDept> deptList = sysDeptMapper.getChildDeptListByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(deptList)) {
                for (SysDept dept : deptList) {
                    String level = dept.getLevel();
                    if (level.indexOf(oldLevelPrefix) == 0) {
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        dept.setLevel(level);
                    }
                }
                sysDeptMapper.batchUpdateLevel(deptList);
            }
        }
        sysDeptMapper.updateByPrimaryKey(after);
    }

    @Override
    public void delete(int deptId) {
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        Preconditions.checkNotNull(dept, "待删除的部门不存在，无法删除");
        if (sysDeptMapper.countByParentId(dept.getId()) > 0) {
            throw new ParamException("当前部门下面有子部门，无法删除");
        }
        if (sysUserMapper.countByDeptId(dept.getId()) > 0) {
            throw new ParamException("当前部门下面有用户，无法删除");
        }
        sysDeptMapper.deleteByPrimaryKey(deptId);
    }

    /**
     * 检查当前部门名称是否存在
     *
     * @param parentId
     * @param deptName
     * @param deptId
     * @return
     */
    private boolean checkExist(Integer parentId, String deptName, Integer deptId) {
        return sysDeptMapper.countByNameAndParentId(parentId, deptName, deptId) > 0;
    }

    /**
     * 获取当前部门等级
     *
     * @param deptId
     * @return
     */
    private String getLevel(Integer deptId) {
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (null != dept) {
            return dept.getLevel();
        }
        return null;
    }

}
